package com.hp.bon.sgw.util;

import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.hp.bon.sgw.domain.ConvMapInfo;

/**
 * 将 dictionayxml中的AVP数据导出
 * 
 * @author wuzhih
 * 
 */
public class DicXmlExport {

	@SuppressWarnings("unchecked")
	public static Collection<ConvMapInfo> exportDicXMLAVPs(InputStream xmlFile) {
		Collection<ConvMapInfo> allBeans = new LinkedList<ConvMapInfo>();

		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(xmlFile);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element rootEL = document.getRootElement();
		List<Element> allEls = new LinkedList<Element>(rootEL.element(
				"application").elements("avp"));
		allEls.addAll(rootEL.element("base").elements("avp"));
		Set<Integer> allCodesSet = new HashSet<Integer>();
		for (Element rowEL : allEls) {
			String avpName = rowEL.attributeValue("name").trim();
			String avpCode = rowEL.attributeValue("code").trim();
			// System.out.println(avpName);
			Element typeEl = rowEL.element("type");
			String avpType = null;
			if (typeEl != null) {
				avpType = typeEl.attributeValue("type-name").trim();
			} else {
				avpType = (rowEL.element("grouped") == null) ? null : "grouped";
			}
			String venderID = rowEL.attributeValue("vendor-id");
			ConvMapInfo avpDefBean = new ConvMapInfo();
			avpDefBean.setAvpName(avpName);
			avpDefBean.setAvpCode(Integer.parseInt(avpCode));
			avpDefBean.setAvpType(avpType);
			avpDefBean.setXmlTag(avpName);// 从字典加载时XMLTag等同于AVP
			avpDefBean.setVenderID(venderID == null ? 0 : Integer
					.parseInt(venderID));
			allBeans.add(avpDefBean);
			if (allCodesSet.contains(avpDefBean.getAvpCode())) {
				System.out.println("code duplicated " + avpDefBean.getAvpCode()
						+ " name " + avpDefBean.getAvpName());
			} else {
				allCodesSet.add(avpDefBean.getAvpCode());
			}
		}
		return allBeans;
	}

	public static void main(String[] arg) throws DocumentException {
		InputStream instream = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("dictionary.xml");
		Collection<ConvMapInfo> allBeans = exportDicXMLAVPs(instream);
		System.out.println("exported total avps :" + allBeans.size());
	}
}
